package com.tulele.vtool.wechat.handler;

import com.tulele.vtool.model.UserInfo;
import com.tulele.vtool.model.UserOpenIds;
import com.tulele.vtool.service.IUserInfoService;
import com.tulele.vtool.utils.DateUtil;
import com.tulele.vtool.utils.RedisCacheUtil;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;
import java.util.Optional;
//取消关注时触发
@Component
@Slf4j
public class UnsubscribeHandler extends AbstractHandler {

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private RedisCacheUtil redisCacheUtil;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService wxMpService,
                                    WxSessionManager sessionManager) {
        try {
            UserOpenIds userOpenId = new UserOpenIds();
            if(wxMpService!=null && wxMpService.getWxMpConfigStorage()!=null) {
                userOpenId.setGzhCode(wxMpService.getWxMpConfigStorage().getAppId());
            }
            if(wxMessage!=null) {
                userOpenId.setOpenId(wxMessage.getFromUser());
            }
            userOpenId.setType(0);
            userOpenId.setUnSubscribeTime(new Date());
            userInfoService.addUserOpenIds(userOpenId);
        }catch (Exception e) {
            log.error("*****  UnsubscribeHandler addUserOpenIds : " + e.getMessage());
        }

        log.info("unSubscriberOpenId: " + wxMessage.getFromUser() + " eventKey: " + wxMessage.getEventKey());

        // TODO 可以更新本地数据库为取消关注状态
        int finalUserId = Optional.ofNullable(userInfoService.getUserStatusByOpenId(wxMessage.getFromUser())).orElse(0);
        if (finalUserId > 0) {
            UserInfo userInfo = new UserInfo();
            userInfo.setUserId(finalUserId);
            userInfo.setConcernStatus(0);
            userInfo.setModifyTime(DateUtil.getCurDate());

            userInfo.setUnsubscribeTime(DateUtil.getCurDate());
            userInfoService.modifyWxUserInfo(userInfo);

            //取消关注，清除相关redis缓存
            redisCacheUtil.removeSingleCache("newSubWxPushUser" + finalUserId);

            redisCacheUtil.removeSingleCache("wxPushUser" + finalUserId);

            redisCacheUtil.removeSingleCache("NewUserBrandSetPushStatus" + finalUserId);
            redisCacheUtil.removeSingleCache("NewUserVisitPushStatus" + finalUserId);
            redisCacheUtil.removeSingleCache("NewUserShareArticlePushStatus" + finalUserId);
        }

        return null;
    }

}
